<template>
  <el-dialog v-model="dialogVisible" title="开票申请" width="500" class="invoicingPop" :before-close="handleClose">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="企业开票" name="0"></el-tab-pane>
      <el-tab-pane label="个人开票" name="1"></el-tab-pane>
    </el-tabs>

    <el-form :model="model" :rules="rules" ref="formRef" label-width="80">
      <el-form-item label="开票金额">
        <el-input v-model="model.amount" placeholder="请输入开票金额" clearable disabled />
      </el-form-item>
      <el-form-item label="公司名称" prop="name" v-if="activeName==0">
        <el-select @change="handleSelect" v-model="model.name" filterable remote reserve-keyword placeholder="请选择公司名称" :remote-method="remoteMethod" :loading="selectLoading">
          <el-option v-for="(item,index) in enterpriseList" :key="index" :label="item.qymc" :value="item.qymc" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="taxNo" v-else>
        <el-input v-model="model.name" placeholder="请输入名称" clearable disabled />
      </el-form-item>
      <el-form-item label="公司税号" prop="taxNo" v-if="activeName==0">
        <el-input v-model="model.taxNo" placeholder="请输入公司税号" clearable disabled />
      </el-form-item>
      <el-form-item label="税号" prop="taxNo" v-else>
        <el-input v-model="model.taxNo" placeholder="请输入税号" clearable disabled />
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="model.email" placeholder="请输入公司税号" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();
const emit = defineEmits(["fatherMethod"]);

let dialogVisible = ref(false);
let activeName = ref("0");
let model = ref({
  transaction_id: "",
  name: "",
  taxNo: "",
  email: "",
  amount: null,
  remark: "",
  spmc: "",
  gmfMobile: "",
  invoiceUser: "",
});
let loading = ref(false);
let selectLoading = ref(false);
let enterpriseList = ref([]); //企业列表
let timer = null; //定时器
let orderInfo = {}; //订单信息
let rules = ref({
  name: [{ required: true, message: "请选择开票信息抬头", trigger: "blur" }],
  taxNo: [{ required: true, message: "请输入公司税号", trigger: "blur" }],
  email: [{ required: true, message: "请输入接受发票邮箱", trigger: "blur" }],
});

function open(row) {
  activeName.value = "0";
  orderInfo = proxy.$utils.deepcopy(row);
  model.value.invoiceUser = row.userId;
  model.value.amount = row.displayPrice;
  if (row.approvalContent.model.enterprise)
    model.value.name = row.approvalContent.model.enterprise;
  if (row.approvalContent.model.enterpriseTax)
    model.value.taxNo = row.approvalContent.model.enterpriseTax;

  if (row.approvalContent.model.email)
    model.value.email = row.approvalContent.model.email;

  model.value.transaction_id = row.out_trade_no;

  dialogVisible.value = true;
}

let handleClick = (e) => {
  activeName.value = e.index;
  if (activeName.value == 0) {
    model.value.name = orderInfo.approvalContent.model.enterprise;
    model.value.taxNo = orderInfo.approvalContent.model.enterpriseTax;
  } else {
    model.value.name = orderInfo.approvalContent.model.name;
    model.value.taxNo = orderInfo.approvalContent.model.identityCard;
  }
};

function handleClose() {
  if (proxy.$refs.formRef) proxy.$refs.formRef.resetFields();
  emit("fatherMethod"); //列表重新加载
  dialogVisible.value = false;
}

async function submitForm() {
  if (!proxy.$refs.formRef) return;
  await proxy.$refs.formRef.validate((valid, fields) => {
    if (valid) {
      save();
    } else {
      console.log("error submit!", fields);
    }
  });
}

async function save() {
  try {
    loading.value = true;
    await proxy.$apis.applyInvoice({
      data: model.value,
      type: "add",
    });
    timer = setInterval(fetchData, 1000); // 每1秒轮询一次
  } catch (error) {
  } finally {
  }
}

const fetchData = async () => {
  let resp = await proxy.$apis.queryOrder({
    ddlsh: model.value.transaction_id,
  });
  if (resp.hasOwnProperty("status") && ![0, 1].includes(resp.status)) {
    loading.value = false;
    if (resp.status == 2) {
      proxy.$utils.showToast(resp._status);
    } else {
      proxy.$utils.showToast(resp.ycyy, 0);
    }
    clearIntervalFunc();
  }
};

let clearIntervalFunc = () => {
  clearInterval(timer);
  timer = null;
};

const remoteMethod = async (query: string) => {
  if (!query) return;
  try {
    selectLoading.value = true;
    enterpriseList.value = await proxy.$apis.autoMatchCompany({
      key: query,
    });
  } catch (error) {
  } finally {
    selectLoading.value = false;
  }
};

function handleSelect(e) {
  let index = proxy.$utils.findIndexByField(enterpriseList.value, "qymc", e);
  model.value.taxNo = enterpriseList.value[index].nsrsbh;
}

defineExpose({ open });
</script>



<style lang="scss">
.invoicingPop {
  .el-dialog__body {
    padding: 10px 15px;
  }
}
</style>



